package com.example.demo.controller;

import com.example.demo.annotation.ValidGroups;
import com.example.demo.vo.UserValidated;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;


// 参考文档：https://www.cnblogs.com/liconglong/p/11720580.html
//@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/addUser")
    public String addUser(@RequestBody UserValidated user, BindingResult bindResult) {
        UserValidated use1 = new UserValidated();
//        use1.setSalary(1);
        if (use1.getSalary() == 1) {
            System.out.println("----");
        }
        // 如果有错误
        if (bindResult.hasErrors()) {
            // 返回提示信息
            return Objects.requireNonNull(bindResult.getFieldError()).getDefaultMessage();

        }
        UserValidated user1 = new UserValidated();
        return "ok";
    }

    // 验证可进行分组。
    @PostMapping("/updateUser")
    public String updateUser(@Validated(value = {ValidGroups.Update.class,ValidGroups.Default.class}) @ModelAttribute @RequestBody UserValidated user, BindingResult bindResult) {
        // 如果有错误
        if (bindResult.hasErrors()) {
            // 返回提示信息
            return Objects.requireNonNull(bindResult.getFieldError()).getDefaultMessage();

        }
        UserValidated user1 = new UserValidated();
        return "ok";
    }
}
